package com.ruoyi.reportReview.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.reportInfo.domain.*;
import com.ruoyi.reportInfo.mapper.*;
import com.ruoyi.reportReview.domain.IndustrialReportInfoCompany;
import com.ruoyi.reportReview.domain.IndustrialReportInfoPark;
import com.ruoyi.reportReview.domain.IndustrialReportInfoStation;
import com.ruoyi.reportReview.domain.bo.IndustrialReportTotalInfoBo;
import com.ruoyi.reportReview.domain.bo.ReportReviewBo;
import com.ruoyi.reportReview.domain.vo.*;
import com.ruoyi.reportReview.mapper.IndustrialReportInfoCompanyMapper;
import com.ruoyi.reportReview.mapper.IndustrialReportInfoParkMapper;
import com.ruoyi.reportReview.mapper.IndustrialReportInfoStationMapper;
import com.ruoyi.reportTask.domain.IndustrialReportTask;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.reportReview.domain.bo.IndustrialReportInfoBo;
import com.ruoyi.reportReview.domain.IndustrialReportInfo;
import com.ruoyi.reportReview.mapper.IndustrialReportInfoMapper;
import com.ruoyi.reportReview.service.IIndustrialReportInfoService;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 填报主表Service业务层处理
 *
 * @author yangzhen
 * @date 2025-11-23
 */
@RequiredArgsConstructor
@Service
public class IndustrialReportInfoServiceImpl implements IIndustrialReportInfoService {

    private final IndustrialReportInfoMapper baseMapper;
    private final IndustrialReportInfoParkMapper industrialReportInfoParkMapper;
    private final IndustrialReportInfoStationMapper industrialReportInfoStationMapper;
    private final IndustrialReportInfoCompanyMapper industrialReportInfoCompanyMapper;

    private final IndustrialLogisticsCompanyLineMapper industrialLogisticsCompanyLineMapper;
    private final IndustrialLogisticsCompanyLineOperationMapper industrialLogisticsCompanyLineOperationMapper;
    private final IndustrialLogisticsCompanyMapper industrialLogisticsCompanyMapper;
    private final IndustrialLogisticsCompanyStoreMapper industrialLogisticsCompanyStoreMapper;
    private final IndustrialParkMapper industrialParkMapper;
    private final IndustrialStationMapper industrialStationMapper;
    private final IndustrialStationOperationInfoMapper industrialStationOperationInfoMapper;
    private final IndustrialLogisticsCompanyOperationMapper industrialLogisticsCompanyOperationMapper;


    /**
     * 查询填报主表
     */
    @Override
    public IndustrialReportInfoVo queryById(String id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询填报主表列表
     */
    @Override
    public TableDataInfo<IndustrialReportInfoVo> queryPageList(IndustrialReportInfoBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<IndustrialReportInfo> lqw = buildQueryWrapper(bo);
        Page<IndustrialReportInfoVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询填报主表列表
     */
    @Override
    public List<IndustrialReportInfoVo> queryList(IndustrialReportInfoBo bo) {
        LambdaQueryWrapper<IndustrialReportInfo> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<IndustrialReportInfo> buildQueryWrapper(IndustrialReportInfoBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<IndustrialReportInfo> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getTaskId()), IndustrialReportInfo::getTaskId, bo.getTaskId());
        lqw.like(StringUtils.isNotBlank(bo.getReportUser()), IndustrialReportInfo::getReportUser, bo.getReportUser());
        lqw.like(StringUtils.isNotBlank(bo.getReportUserPhone()), IndustrialReportInfo::getReportUserPhone, bo.getReportUserPhone());
        lqw.like(StringUtils.isNotBlank(bo.getTitleName()), IndustrialReportInfo::getTitleName, bo.getTitleName());
        lqw.eq(bo.getDataStatus() != null, IndustrialReportInfo::getDataStatus, bo.getDataStatus());
        lqw.eq(bo.getCollectDate() != null, IndustrialReportInfo::getCollectDate, bo.getCollectDate());
        lqw.like(StringUtils.isNotBlank(bo.getTaskName()), IndustrialReportInfo::getTaskName, bo.getTaskName());

        lqw.between(params.get("beginCreateTime") != null && params.get("endCreateTime") != null,
            IndustrialReportInfo::getCreateTime, params.get("beginCreateTime"), params.get("endCreateTime"));
        return lqw;
    }

    /**
     * 新增填报主表
     */
    @Override
    public Boolean insertByBo(IndustrialReportInfoBo bo) {
        IndustrialReportInfo add = BeanUtil.toBean(bo, IndustrialReportInfo.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改填报主表
     */
    @Override
    public Boolean updateByBo(IndustrialReportInfoBo bo) {
        IndustrialReportInfo update = BeanUtil.toBean(bo, IndustrialReportInfo.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(IndustrialReportInfo entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除填报主表
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertReportTotalInfo(IndustrialReportTotalInfoBo bo) throws IllegalAccessException {
        if (bo == null) {
            throw new IllegalAccessException("主信息参数缺失");
        }
        if (bo.getHeader() == null) {
            throw new IllegalAccessException("主信息参数缺失");
        }
        // ---------------- 0. 验证截止日期 ----------------
        IndustrialReportInfo header = bo.getHeader();

        if (StringUtils.isBlank(header.getReportUser())) {
            throw new IllegalAccessException("填报人(reportUser)不能为空");
        }
        if (StringUtils.isBlank(header.getReportUserPhone())) {
            throw new IllegalAccessException("填报人手机号(reportUserPhone)不能为空");
        }
        if (header.getDeadline() != null && !header.getDeadline().isEmpty()) {

            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date deadlineDate = sdf.parse(header.getDeadline());
                if (new Date().after(deadlineDate)) {
                    throw new IllegalAccessException("已超过填报截止日期: " + header.getDeadline());
                }
            } catch (Exception e) {
                throw new IllegalAccessException("截止日期解析失败: " + header.getDeadline());
            }
        }
        // ---------------- 1. 新增主表 ----------------
        header.setCreateBy(header.getReportUser());
        header.setUpdateBy(header.getReportUser());
        header.setDataStatus(1L);
        baseMapper.insert(header);
        String mainId = header.getId(); // 主表id

        // ---------------- 2. 新增园区信息 ----------------
        IndustrialReportInfoPark park = bo.getPark();
        if (park != null && StringUtils.isNotBlank(park.getParkName())) {
            park.setInfoId(mainId);
            industrialReportInfoParkMapper.insert(park);
        }

        // ---------------- 3. 新增场站信息 ----------------
        IndustrialReportInfoStation station = bo.getStation();
        if (station != null && StringUtils.isNotBlank(station.getStationName())) {
            station.setInfoId(mainId);
            industrialReportInfoStationMapper.insert(station);
        }

        // =====================================================
        // 4. 新增企业信息（含仓库、专线校验）
        // =====================================================
        IndustrialReportInfoCompany company = bo.getCompany();
        if (company != null && StringUtils.isNotBlank(company.getCompanyName())) {

            company.setInfoId(mainId);

            // -----------（新增校验）解析 storeList（仓库列表）-------------
            if (StringUtils.isNotBlank(company.getStoreList())) {
                List<IndustrialLogisticsCompanyStore> storeList =
                    JSONUtil.toList(company.getStoreList(), IndustrialLogisticsCompanyStore.class);

                // Duplicate name check
                Set<String> nameSet = new HashSet<>();
                for (IndustrialLogisticsCompanyStore s : storeList) {
                    if (!nameSet.add(s.getStoreName())) {
                        throw new IllegalAccessException("仓库名称重复: " + s.getStoreName());
                    }
                }
            }

            // -----------（新增校验）解析 dedicatedLineList（专线列表）-------------
            if (StringUtils.isNotBlank(company.getDedicatedLineList())) {
                List<IndustrialLogisticsCompanyLine> lineList =
                    JSONUtil.toList(company.getDedicatedLineList(), IndustrialLogisticsCompanyLine.class);

                // key = startPoint + endPoint
                Set<String> lineKeySet = new HashSet<>();
                for (IndustrialLogisticsCompanyLine line : lineList) {
                    String key = line.getStartPoint() + "->" + line.getEndPoint();
                    if (!lineKeySet.add(key)) {
                        throw new IllegalAccessException("专线起点和终点重复: " + key);
                    }
                }
            }
            industrialReportInfoCompanyMapper.insert(company);
        }
        return true;
    }

    @Override
    public IndustrialReportTotalInfoVo getReportInfoById(String id) {
        IndustrialReportTotalInfoVo industrialReportTotalInfoVo = new IndustrialReportTotalInfoVo();
        IndustrialReportInfoVo industrialReportInfoVo = baseMapper.selectVoById(id);
        if (industrialReportInfoVo == null) {
            return null;
        }
        IndustrialReportInfoParkVo industrialReportInfoParkVo = industrialReportInfoParkMapper.selectVoOne(new LambdaQueryWrapper<IndustrialReportInfoPark>().eq(IndustrialReportInfoPark::getInfoId, id));
        IndustrialReportInfoStationVo industrialReportInfoStationVo = industrialReportInfoStationMapper.selectVoOne(new LambdaQueryWrapper<IndustrialReportInfoStation>().eq(IndustrialReportInfoStation::getInfoId, id));
        IndustrialReportInfoCompanyVo industrialReportInfoCompanyVo = industrialReportInfoCompanyMapper.selectVoOne(new LambdaQueryWrapper<IndustrialReportInfoCompany>().eq(IndustrialReportInfoCompany::getInfoId, id));
        industrialReportTotalInfoVo.setHeader(industrialReportInfoVo);
        industrialReportTotalInfoVo.setPark(industrialReportInfoParkVo);
        industrialReportTotalInfoVo.setStation(industrialReportInfoStationVo);
        industrialReportTotalInfoVo.setCompany(industrialReportInfoCompanyVo);
        return industrialReportTotalInfoVo;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean review(ReportReviewBo bo) {

        String id = bo.getId();
        String action = bo.getAction();
        Date now = new Date();
        String username = LoginHelper.getUsername();

        // ① 查询主表
        IndustrialReportInfoVo infoVo = baseMapper.selectVoById(id);
        if (infoVo == null) {
            throw new ServiceException("未找到填报数据 id=" + id);
        }

        Date reportCollectDate = infoVo.getReportCollectDate();

        // =============== ① 审核通过：拆分并入正式库（存在修改，不存在新增） ==================
        if ("approve".equalsIgnoreCase(action)) {

            /**
             * ===================== 1.园区表（信息简单 → 直接转实体） =====================
             */
            IndustrialReportInfoParkVo parkVo =
                industrialReportInfoParkMapper.selectVoOne(
                    new LambdaQueryWrapper<IndustrialReportInfoPark>()
                        .eq(IndustrialReportInfoPark::getInfoId, id)
                );

            if (parkVo != null) {
                IndustrialPark park = BeanUtil.toBean(parkVo, IndustrialPark.class);

                // 查重：ID优先，其次统一社会代码
                IndustrialPark exist = industrialParkMapper.selectOne(
                    Wrappers.<IndustrialPark>lambdaQuery()
                        .eq(StringUtils.isNotBlank(park.getUnifiedSocialCode()),
                            IndustrialPark::getUnifiedSocialCode, park.getUnifiedSocialCode())
                        .eq(StringUtils.isNotBlank(park.getParkName()),
                            IndustrialPark::getParkName, park.getParkName())
                );

                if (exist != null) {
                    park.setId(exist.getId());
                    park.setUpdateBy(username);
                    park.setUpdateTime(now);
                    industrialParkMapper.updateById(park);
                } else {
                    park.setCreateBy(username);
                    park.setCreateTime(now);
                    park.setDataSources("report"); // 数据来源：填报
                    industrialParkMapper.insert(park);
                }
            }


            /**
             * ===================== 2.场站：拆分 Station + Operation =====================
             */
            IndustrialReportInfoStationVo stationVo =
                industrialReportInfoStationMapper.selectVoOne(
                    new LambdaQueryWrapper<IndustrialReportInfoStation>()
                        .eq(IndustrialReportInfoStation::getInfoId, id)
                );

            if (stationVo != null) {

                // 2.1 拆出来 Station 主表
                IndustrialStation station = BeanUtil.toBean(stationVo, IndustrialStation.class);

                // 查重 Station
                IndustrialStation existStation = industrialStationMapper.selectOne(
                    Wrappers.<IndustrialStation>lambdaQuery()
                        .eq(StringUtils.isNotBlank(station.getUnifiedSocialCode()),
                            IndustrialStation::getUnifiedSocialCode, station.getUnifiedSocialCode())
                        .eq(StringUtils.isNotBlank(station.getStationName()),
                            IndustrialStation::getStationName, station.getStationName())
                );

                if (existStation != null) {
                    station.setId(existStation.getId());
                    station.setUpdateBy(username);
                    station.setUpdateTime(now);
                    industrialStationMapper.updateById(station);
                } else {
                    station.setCreateBy(username);
                    station.setCreateTime(now);
                    station.setDataSources("report"); // 数据来源：填报
                    industrialStationMapper.insert(station);
                }

                String stationId = station.getId();

                // 2.2 拆出来 Operation 列表（JSON）
                if (stationVo.getCarNum() != null || stationVo.getFreightVolume() != null) {
                    IndustrialStationOperationInfo op = new IndustrialStationOperationInfo();
                    op.setStationId(stationId);
                    op.setReportCollectDate(reportCollectDate);
                    op.setReportCycle(infoVo.getReportCycle());
                    op.setCarNum(stationVo.getCarNum());
                    op.setFreightVolume(stationVo.getFreightVolume());
                    op.setReportDate(now);
                    // 唯一：station_id + report_date
                    IndustrialStationOperationInfo existOp = industrialStationOperationInfoMapper.selectOne(
                        Wrappers.<IndustrialStationOperationInfo>lambdaQuery()
                            .eq(IndustrialStationOperationInfo::getStationId, stationId)
                            .eq(IndustrialStationOperationInfo::getReportCollectDate, op.getReportCollectDate())
                    );

                    if (existOp != null) {
                        op.setId(existOp.getId());
                        op.setUpdateBy(username);
                        op.setUpdateTime(now);
                        op.setReportCycle(infoVo.getReportCycle());
                        industrialStationOperationInfoMapper.updateById(op);
                    } else {
                        op.setCreateBy(username);
                        op.setCreateTime(now);
                        op.setReportCycle(infoVo.getReportCycle());
                        industrialStationOperationInfoMapper.insert(op);
                    }

                }
            }


            /**
             * ===================== 3.企业：Company + Line + Store + Operation =====================
             */
            IndustrialReportInfoCompanyVo companyVo =
                industrialReportInfoCompanyMapper.selectVoOne(
                    new LambdaQueryWrapper<IndustrialReportInfoCompany>()
                        .eq(IndustrialReportInfoCompany::getInfoId, id)
                );

            if (companyVo != null) {

                // 3.1 拆 Company 主表
                IndustrialLogisticsCompany company = BeanUtil.toBean(companyVo, IndustrialLogisticsCompany.class);

                IndustrialLogisticsCompany existCompany = industrialLogisticsCompanyMapper.selectOne(
                    Wrappers.<IndustrialLogisticsCompany>lambdaQuery()
                        .eq(StringUtils.isNotBlank(company.getUnifiedSocialCode()),
                            IndustrialLogisticsCompany::getUnifiedSocialCode, company.getUnifiedSocialCode())
                );

                if (existCompany != null) {
                    company.setId(existCompany.getId());
                    company.setUpdateBy(username);
                    company.setUpdateTime(now);
                    industrialLogisticsCompanyMapper.updateById(company);
                } else {
                    company.setCreateBy(username);
                    company.setCreateTime(now);
                    company.setDataSources("report");
                    industrialLogisticsCompanyMapper.insert(company);
                }

                String companyId = company.getId();


                /**
                 * =============== 3.2 专线 LineList （JSON） → 同步策略：以 JSON 为准（新增/更新/删除） ===============
                 */
                if (StringUtils.isNotBlank(companyVo.getDedicatedLineList())) {
                    List<IndustrialLogisticsCompanyLine> lineList =
                        JSONUtil.toList(companyVo.getDedicatedLineList(), IndustrialLogisticsCompanyLine.class);

                    // 用于按“唯一 key”快速匹配新数据（优先使用 id 匹配；否则使用 start+end）
                    Map<String, IndustrialLogisticsCompanyLine> newMap = new HashMap<>();
                    for (IndustrialLogisticsCompanyLine line : lineList) {
                        line.setCompanyId(companyId);
                        line.setReportCollectDate(reportCollectDate);
                        // key：如果 JSON 带 id，优先用 id，否则用 start||end（trim）
                        String key;
                        if (StringUtils.isNotBlank(line.getId())) {
                            key = "ID::" + line.getId();
                        } else {
                            String start = StringUtils.trimToEmpty(line.getStartPoint());
                            String end = StringUtils.trimToEmpty(line.getEndPoint());
                            key = "SE::" + start + "||" + end;
                        }
                        newMap.put(key, line);
                    }

                    // 查询数据库中当前公司已有的专线
                    List<IndustrialLogisticsCompanyLine> existLines =
                        industrialLogisticsCompanyLineMapper.selectList(
                            Wrappers.<IndustrialLogisticsCompanyLine>lambdaQuery()
                                .eq(IndustrialLogisticsCompanyLine::getCompanyId, companyId)
                        );

                    // matched keys
                    Set<String> matched = new HashSet<>();

                    // 1) 遍历已有的：若在 newMap 中则更新；若不在则删除
                    for (IndustrialLogisticsCompanyLine existLine : existLines) {
                        // 先构造相同规则的 key 去匹配
                        String existKey;
                        if (StringUtils.isNotBlank(existLine.getId())) {
                            existKey = "ID::" + existLine.getId();
                        } else {
                            String start = StringUtils.trimToEmpty(existLine.getStartPoint());
                            String end = StringUtils.trimToEmpty(existLine.getEndPoint());
                            existKey = "SE::" + start + "||" + end;
                        }

                        IndustrialLogisticsCompanyLine newLine = newMap.get(existKey);

                        if (newLine != null) {
                            // 更新：用 newLine 的内容覆盖 existLine 的 id（保持 id 不变）
                            newLine.setId(existLine.getId());
                            newLine.setCompanyId(company.getId());
                            newLine.setCompanyName(company.getCompanyName());
                            newLine.setUpdateBy(username);
                            newLine.setUpdateTime(now);
                            // 保证 dataSources/reportCollectDate/companyId 等字段被设置
                            if (StringUtils.isBlank(newLine.getDataSources())) {
                                newLine.setDataSources("report");
                            }
                            industrialLogisticsCompanyLineMapper.updateById(newLine);
                            matched.add(existKey);
                        } else {
                            // 数据库中存在但 JSON 中没有 -> 删除
                            industrialLogisticsCompanyLineMapper.deleteById(existLine.getId());
                        }
                    }

                    // 2) 对 newMap 中未匹配到的项插入（新增）
                    for (Map.Entry<String, IndustrialLogisticsCompanyLine> e : newMap.entrySet()) {
                        if (matched.contains(e.getKey())) continue;
                        IndustrialLogisticsCompanyLine lineToInsert = e.getValue();
                        lineToInsert.setCreateBy(username);
                        lineToInsert.setCreateTime(now);
                        lineToInsert.setCompanyId(company.getId());
                        lineToInsert.setCompanyName(company.getCompanyName());
                        lineToInsert.setDataSources("report");
                        industrialLogisticsCompanyLineMapper.insert(lineToInsert);
                    }
                }


                /**
                 * =============== 3.3 仓库 StoreList （JSON） → 同步策略：以 JSON 为准（新增/更新/删除） ===============
                 */
                if (StringUtils.isNotBlank(companyVo.getStoreList())) {
                    List<IndustrialLogisticsCompanyStore> storeList =
                        JSONUtil.toList(companyVo.getStoreList(), IndustrialLogisticsCompanyStore.class);

                    Map<String, IndustrialLogisticsCompanyStore> newStoreMap = new HashMap<>();
                    for (IndustrialLogisticsCompanyStore store : storeList) {
                        store.setCompanyId(companyId);
                        // 匹配 key：优先 id，否则使用 storeName（trim）
                        String key;
                        if (StringUtils.isNotBlank(store.getId())) {
                            key = "ID::" + store.getId();
                        } else {
                            key = "NAME::" + StringUtils.trimToEmpty(store.getStoreName());
                        }
                        newStoreMap.put(key, store);
                    }

                    List<IndustrialLogisticsCompanyStore> existStores =
                        industrialLogisticsCompanyStoreMapper.selectList(
                            Wrappers.<IndustrialLogisticsCompanyStore>lambdaQuery()
                                .eq(IndustrialLogisticsCompanyStore::getCompanyId, companyId)
                        );

                    Set<String> matchedStoreKeys = new HashSet<>();

                    for (IndustrialLogisticsCompanyStore existStore : existStores) {
                        String existKey;
                        if (StringUtils.isNotBlank(existStore.getId())) {
                            existKey = "ID::" + existStore.getId();
                        } else {
                            existKey = "NAME::" + StringUtils.trimToEmpty(existStore.getStoreName());
                        }

                        IndustrialLogisticsCompanyStore newStore = newStoreMap.get(existKey);

                        if (newStore != null) {
                            // 更新
                            newStore.setId(existStore.getId());
                            newStore.setUpdateBy(username);
                            newStore.setUpdateTime(now);
                            newStore.setCompanyId(company.getId());
                            newStore.setCompanyName(company.getCompanyName());
                            if (StringUtils.isBlank(newStore.getDataSources())) {
                                newStore.setDataSources("report");
                            }
                            industrialLogisticsCompanyStoreMapper.updateById(newStore);
                            matchedStoreKeys.add(existKey);
                        } else {
                            // 存在数据库但 JSON 没有 -> 删除
                            industrialLogisticsCompanyStoreMapper.deleteById(existStore.getId());
                        }
                    }

                    // 插入 newMap 中未匹配到的项
                    for (Map.Entry<String, IndustrialLogisticsCompanyStore> e : newStoreMap.entrySet()) {
                        if (matchedStoreKeys.contains(e.getKey())) continue;
                        IndustrialLogisticsCompanyStore storeToInsert = e.getValue();
                        storeToInsert.setCreateBy(username);
                        storeToInsert.setCreateTime(now);
                        storeToInsert.setCompanyId(company.getId());
                        storeToInsert.setCompanyName(company.getCompanyName());
                        storeToInsert.setDataSources("report");
                        industrialLogisticsCompanyStoreMapper.insert(storeToInsert);
                    }
                }

                /**
                 * =============== 3.4 企业运营 StoreList （JSON） ===============
                 */
                if (companyVo.getOperationCars() != null || companyVo.getOperationWeight() != null) {
                    IndustrialLogisticsCompanyOperation op = new IndustrialLogisticsCompanyOperation();
                    op.setCompanyId(companyId);
                    op.setReportCollectDate(reportCollectDate);
                    op.setReportCycle(infoVo.getReportCycle());
                    op.setOperationCars(companyVo.getOperationCars());
                    op.setOperationWeight(companyVo.getOperationWeight());

                    IndustrialLogisticsCompanyOperation existCompanyOperation = industrialLogisticsCompanyOperationMapper.selectOne(
                        Wrappers.<IndustrialLogisticsCompanyOperation>lambdaQuery()
                            .eq(IndustrialLogisticsCompanyOperation::getCompanyId, companyId)
                            .eq(IndustrialLogisticsCompanyOperation::getReportCollectDate, op.getReportCollectDate())
                    );

                    if (existCompanyOperation != null) {
                        op.setId(existCompanyOperation.getId());
                        op.setUpdateBy(username);
                        op.setUpdateTime(now);
                        industrialLogisticsCompanyOperationMapper.updateById(op);
                    } else {
                        op.setCreateBy(username);
                        op.setCreateTime(now);
                        industrialLogisticsCompanyOperationMapper.insert(op);
                    }
                }


                /**
                 * =============== 3.5 专线运营 OperationList （JSON） ===============
                 */
                if (StringUtils.isNotBlank(companyVo.getOperationList())) {
                    List<IndustrialLogisticsCompanyLineOperation> opList = JSONUtil.toList(companyVo.getOperationList(), IndustrialLogisticsCompanyLineOperation.class);

                    for (IndustrialLogisticsCompanyLineOperation op : opList) {
                        op.setCompanyId(companyId);
                        op.setReportCycle(infoVo.getReportCycle());
                        op.setReportCycle(infoVo.getReportCycle());

                        IndustrialLogisticsCompanyLineOperation existOp =
                            industrialLogisticsCompanyLineOperationMapper.selectOne(
                                Wrappers.<IndustrialLogisticsCompanyLineOperation>lambdaQuery()
                                    .eq(IndustrialLogisticsCompanyLineOperation::getCompanyId, companyId)
                                    .eq(IndustrialLogisticsCompanyLineOperation::getReportDate, op.getReportDate())
                                    .eq(IndustrialLogisticsCompanyLineOperation::getStartPoint, op.getStartPoint())
                                    .eq(IndustrialLogisticsCompanyLineOperation::getEndPoint, op.getEndPoint())
                            );

                        if (existOp != null) {
                            op.setId(existOp.getId());
                            op.setUpdateBy(username);
                            op.setUpdateTime(now);
                            industrialLogisticsCompanyLineOperationMapper.updateById(op);
                        } else {
                            op.setCreateBy(username);
                            op.setCreateTime(now);
                            industrialLogisticsCompanyLineOperationMapper.insert(op);
                        }
                    }
                }
            }


            /**
             * ===================== 4. 更新主表审核状态 =====================
             */
            IndustrialReportInfo update = new IndustrialReportInfo();
            update.setId(id);
            update.setDataStatus(2L); // 审核通过
            update.setReviewDesc(bo.getReviewDesc());
            update.setReviewBy(username);
            update.setReviewTime(now);
            baseMapper.updateById(update);
            return true;
        }


        // =============== ② 审核驳回：只更新主表 ==================
        if ("reject".equalsIgnoreCase(action)) {
            IndustrialReportInfo update = new IndustrialReportInfo();
            update.setId(id);
            update.setDataStatus(3L); // 审核驳回
            update.setReviewDesc(bo.getReviewDesc());
            update.setReviewBy(username);
            update.setReviewTime(now);
            baseMapper.updateById(update);
            return true;
        }

        throw new ServiceException("非法的审核动作 action=" + action);
    }


}
